package cn.chitanda.weather.ui.AddCity


import android.content.Context
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import cn.chitanda.weather.R
import cn.chitanda.weather.data.TAG
import cn.chitanda.weather.ui.PlaceViewModel
import com.jaeger.library.StatusBarUtil
import kotlinx.android.synthetic.main.fragment_add_city.*

/**
 * A simple [Fragment] subclass.
 */
class AddCityFragment : Fragment() {
    private val viewmodel: PlaceViewModel by lazy {
        ViewModelProvider(
            this,
            ViewModelProvider.AndroidViewModelFactory(requireActivity().application)
        ).get(PlaceViewModel::class.java)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_add_city, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        StatusBarUtil.setLightMode(requireActivity())
        val resultAdapter = ResultAdapter(viewmodel)
        searchResultRecycler.apply {
            adapter = resultAdapter
            layoutManager = LinearLayoutManager(requireContext())
        }
        viewmodel.searchResult.observe(this, Observer {
            resultAdapter.submitList(it)
            Log.d(TAG, resultAdapter.itemCount.toString())
        })
        val watcher = object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                val string = addCity_EditText.text.toString()
                viewmodel.searchCity(string)
            }
        }
        addCity_EditText.addTextChangedListener(watcher)

        addCity_TB.setNavigationOnClickListener { findNavController().navigateUp() }

    }

    private fun hideSoftInput(v: View) {
        val manager: InputMethodManager? =
            requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?
        manager?.hideSoftInputFromWindow(v.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
    }

    override fun onStop() {
        super.onStop()
        hideSoftInput(requireView())
    }
}
